#!/usr/bin/env python
# -*- coding: utf-8 -*-

"""
QTorch外汇和ETF资产示例脚本
展示如何使用QTorch框架进行外汇和ETF资产的回测
"""

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from datetime import datetime, timedelta

from qtorch.core.qengine import QEngine
from qtorch.data.multi_asset_fetcher import MultiAssetFetcher
from qtorch.strategy.dual_moving_average import DualMovingAverageStrategy

def run_forex_backtest():
    """运行外汇回测示例"""
    print("=" * 50)
    print("外汇回测示例")
    print("=" * 50)
    
    # 创建回测引擎
    engine = QEngine()
    
    # 设置回测参数
    start_date = "2023-01-01"
    end_date = "2023-12-31"
    symbol = "EURUSD.FOREX"  # 欧元/美元外汇对
    
    # 设置策略参数
    fast_period = 5
    slow_period = 20
    
    # 创建策略
    strategy = DualMovingAverageStrategy(fast_period=fast_period, slow_period=slow_period)
    
    # 配置回测引擎
    engine.set_capital(10000)  # 初始资金
    engine.set_commission(0.0001)  # 手续费0.01%
    engine.set_slippage(0.0002)  # 滑点0.02%
    
    # 设置多资产数据获取器
    data_fetcher = MultiAssetFetcher()
    engine.set_data_provider(data_fetcher)
    
    # 运行回测
    result = engine.run_backtest(
        symbol=symbol,
        strategy=strategy,
        start_date=start_date,
        end_date=end_date,
        asset_type="forex"  # 指定资产类型为外汇
    )
    
    # 打印回测结果
    print(f"总收益率: {result['total_return']:.2%}")
    print(f"年化收益率: {result['annual_return']:.2%}")
    print(f"最大回撤: {result['max_drawdown']:.2%}")
    print(f"夏普比率: {result['sharpe_ratio']:.2f}")
    
    # 绘制回测结果
    engine.plot_results()
    
    return result

def run_etf_backtest():
    """运行ETF回测示例"""
    print("=" * 50)
    print("ETF回测示例")
    print("=" * 50)
    
    # 创建回测引擎
    engine = QEngine()
    
    # 设置回测参数
    start_date = "2023-01-01"
    end_date = "2023-12-31"
    symbol = "sh510300"  # 沪深300ETF
    
    # 设置策略参数
    fast_period = 10
    slow_period = 30
    
    # 创建策略
    strategy = DualMovingAverageStrategy(fast_period=fast_period, slow_period=slow_period)
    
    # 配置回测引擎
    engine.set_capital(100000)  # 初始资金
    engine.set_commission(0.0003)  # 手续费0.03%
    engine.set_slippage(0.0005)  # 滑点0.05%
    
    # 设置多资产数据获取器
    data_fetcher = MultiAssetFetcher()
    engine.set_data_provider(data_fetcher)
    
    # 运行回测
    result = engine.run_backtest(
        symbol=symbol,
        strategy=strategy,
        start_date=start_date,
        end_date=end_date,
        asset_type="etf"  # 指定资产类型为ETF
    )
    
    # 打印回测结果
    print(f"总收益率: {result['total_return']:.2%}")
    print(f"年化收益率: {result['annual_return']:.2%}")
    print(f"最大回撤: {result['max_drawdown']:.2%}")
    print(f"夏普比率: {result['sharpe_ratio']:.2f}")
    
    # 绘制回测结果
    engine.plot_results()
    
    return result

def run_multi_asset_comparison():
    """运行多资产对比示例"""
    print("=" * 50)
    print("多资产对比示例")
    print("=" * 50)
    
    # 设置回测参数
    start_date = "2023-01-01"
    end_date = "2023-12-31"
    
    # 创建多资产数据获取器
    data_fetcher = MultiAssetFetcher()
    
    # 获取不同资产类型的数据
    assets = {
        "沪深300ETF": {"symbol": "sh510300", "type": "etf"},
        "欧元/美元": {"symbol": "EURUSD.FOREX", "type": "forex"},
        "上证指数": {"symbol": "sh000001", "type": "stock"},
        "比特币": {"symbol": "BTC.BTC", "type": "crypto"}
    }
    
    # 存储各资产的收益率数据
    returns_data = {}
    
    # 获取各资产数据并计算收益率
    for name, asset in assets.items():
        try:
            # 获取资产数据
            df = data_fetcher.get_market_data(
                symbol=asset["symbol"],
                start_date=start_date,
                end_date=end_date,
                asset_type=asset["type"]
            )
            
            # 计算累积收益率
            if not df.empty and 'returns' in df.columns:
                cumulative_returns = (1 + df['returns']).cumprod() - 1
                returns_data[name] = cumulative_returns
                
                # 打印资产信息
                print(f"{name} 总收益率: {cumulative_returns.iloc[-1]:.2%}")
        except Exception as e:
            print(f"获取{name}数据失败: {str(e)}")
    
    # 绘制多资产收益率对比图
    if returns_data:
        plt.figure(figsize=(12, 6))
        for name, returns in returns_data.items():
            plt.plot(returns.index, returns.values, label=name)
        
        plt.title('多资产累积收益率对比')
        plt.xlabel('日期')
        plt.ylabel('累积收益率')
        plt.legend()
        plt.grid(True)
        plt.tight_layout()
        plt.show()

if __name__ == "__main__":
    # 运行外汇回测示例
    forex_result = run_forex_backtest()
    
    # 运行ETF回测示例
    etf_result = run_etf_backtest()
    
    # 运行多资产对比示例
    run_multi_asset_comparison()